using System;
using System.Globalization;

namespace ShopPowerTemplate.Common.Validation
{
    public class RequiredNumberValidationControl : ShopPowerTemplate.Common.Validation.ValidationControl
    {
        public RequiredNumberValidationControl()
            : base()
        {
            ValidationMessage.Text = "* Number expected";
        }

        public override bool Validate()
        {
            bool result = IsNumeric(PropertyToValidate);
            ValidationMessage.Visibility = result ? Windows.UI.Xaml.Visibility.Collapsed : Windows.UI.Xaml.Visibility.Visible;
            return result;
        }

        private static System.Boolean IsNumeric(System.Object Expression)
        {
            if (Expression == null || Expression is DateTime)
                return false;

            if (Expression is Int16 || Expression is Int32 || Expression is Int64 || Expression is Decimal || Expression is Single || Expression is Double || Expression is Boolean)
                return true;

            try
            {
                CultureInfo cultureInfo = CultureInfo.CurrentUICulture;
                if (Expression is string)
                    Double.Parse(Expression as string, cultureInfo.NumberFormat);
                else
                    Double.Parse(Expression.ToString(), cultureInfo.NumberFormat);
                return true;
            }
            catch { } // just dismiss errors but return false
            return false;
        }
    }
}
